<template>
  <div>
    <!--面包屑导航-->
    <Breadcrumb>
      <template #firstTitle>
        <span>商品管理</span>
      </template>
      <template #secondTitle>
        <span>参数列表</span>
      </template>
    </Breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--警告文字-->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>

      <!--选择商品分类-->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类：</span>
          <!--选择商品分类的连级选择框-->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable></el-cascader>
        </el-col>
      </el-row>

      <!--tab页签-->
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!--动态参数表格-->
          <el-table
            border
            stripe
            :data="manyTableData">
            <!--展开列-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--循环渲染tag标签-->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index + item"
                  @close="removeParams(scope.row, index)">{{item}}</el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"></el-input>
                <!--添加tag按钮-->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!--修改按钮-->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
                <!--删除按钮-->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteOpen(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!--静态属性表格-->
          <el-table
            border
            stripe
            :data="onlyTableData">
            <!--展开列-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--循环渲染tag标签-->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index + item"
                  @close="removeParams(scope.row, index)">{{item}}</el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"></el-input>
                <!--添加tag按钮-->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!--修改按钮-->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
                <!--删除按钮-->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteOpen(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数-->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
      width="50%">
      <!--内容主体-->
      <el-form
        status-icon
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--内容底部-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改参数-->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
      width="50%">
      <!--内容主体-->
      <el-form
        status-icon
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!--内容底部-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Breadcrumb from '@/components/common/Breadcrumb.vue'

  export default {
    name: "GoodsParams",
    data(){
      return{
        cateList: [], //商品分类列表
        parentCateList: [], //父级分类列表
        cascaderProps: {  //指定级联选择器的配置对象
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        selectedKeys: [],  //选中父级分类ID数组
        activeTabName: 'many',  //被激活的页签
        manyTableData: [],  //动态属性数据
        onlyTableData: [],  //静态属性数据
        addDialogVisible: false,  //添加对话框的显示隐藏
        addForm: {  //添加对话框的数据
          attr_name: ''
        },
        addFormRules: { //添加对话框的数据验证
          attr_name: [
            {required: true, message: '请输入参数名称', trigger: 'blur'}
          ],
        },
        editDialogVisible: false, //修对话框的显示隐藏
        editForm: {},//修改对话框的数据
        editFormRules: {  //修改对话框的数据验证
          attr_name: [
            {required: true, message: '请输入参数名称', trigger: 'blur'}
          ],
        },
        inputVisible: false,  //控制添加tag按钮与文本输入框的切换
        inputValue: '', //文本框输入的内容
      }
    },
    components: {
      Breadcrumb
    },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled(){
      if (this.selectedKeys.length !== 3){
        return true;
      }else {
        return false;
      }
    },
    // 当前选中的分类ID
    cateId(){
      if (this.selectedKeys.length === 3){
        return this.selectedKeys[2];
      }else {
        return '';
      }
    },
    // 动态计算标题文本
    titleText(){
      if (this.activeTabName === 'many'){
        return '动态参数';
      } else {
        return '静态属性';
      }
    }
  },
    created() {
      this.getCateList();
    },
    methods:{
      // 获取商品分类数据
      async getCateList(){
        const {data: res} = await this.$http.get('categories');
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(`获取商品分类数据: ${res.meta.msg}`);
          return;
        }
        this.cateList = res.data;
      },
      // 选择商品分类
      parentCateChange() {
        if (this.selectedKeys.length !== 3){
          this.selectedKeys = [];
          this.manyTableData = [];
          this.onlyTableData = [];
          return;
        }
        this.getParamsData();
      },
      // tab页签点击事件
      handleTabClick(){
        this.getParamsData();
      },
      // 获取参数列表数据
      async getParamsData(){
        // 根据所选分类ID和当前所处的面板获取对应的参数
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeTabName}});
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(`获取参数列表: ${res.meta.msg}`);
          return;
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
          // 控制文本框的显示与隐藏
          item.inputVisible = false;
          // 文本框输入的值
          item.inputValue = '';
        });
        if (this.activeTabName === 'many'){
          this.manyTableData = res.data;
        } else {
          this.onlyTableData = res.data;
        }

      },
      // 监听添加对话框的关闭事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      // 添加参数/属性
      addParams(){
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          // 可以发起添加分类请求
          const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,
            {attr_name: this.addForm.attr_name, attr_sel: this.activeTabName});
          // console.log(res);
          if (res.meta.status !== 201) {
            this.$message.error('添加失败');
            this.addDialogVisible = false;
            return;
          }
          this.$message.success('添加成功');
          this.addDialogVisible = false;
          this.getParamsData();
        });
      },
      // 点击修改按钮
      showEditDialog(params){
        this.editForm = params;
        this.editDialogVisible = true;
      },
      // 修改参数/属性
      editParams(){
        this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return;
          // 可以发起添加分类请求
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {attr_name: this.editForm.attr_name, attr_sel: this.activeTabName});
          // console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('修改失败');
            this.editDialogVisible = false;
            return;
          }
          this.$message.success('修改成功');
          this.editDialogVisible = false;
          this.getParamsData();
        });
      },
      // 监听修改对话框的关闭事件
      editDialogClosed(){
        this.editForm = {};
        this.$refs.editFormRef.resetFields();
      },
      // 删除提示对话框
      deleteOpen(id) {
        this.$confirm('此操作将永久删除该参数, 是否继续?', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`);
          // console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('删除失败');
            return;
          }
          this.$message.success('删除成功!');
          this.getParamsData();
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
      // 文本框失去焦点，或者按enter触发
      handleInputConfirm(row){
        if (row.inputValue.trim().length === 0){
          row.inputValue = '';
          row.inputVisible = false;
          return;
        }
        //提交添加的参数/属性
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = '';
        row.inputVisible = false;
        this.saveAttrVals(row);

      },
      // 点击添加tag按钮展示文本框
      showInput(row){
        row.inputVisible = true;
        // 让文本框自动获得焦点
        // $nextTick方法的作用：当页面上的元素重新被渲染之后，才会指定回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 将对attr_vals的操作保存到数据库
      async saveAttrVals(row){
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(' ')
          });
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error('修改参数选项失败');
        }
        this.$message.success('修改参数选项成功');
      },
      // 删除对应的参数可选项
      removeParams(row, index){
        row.attr_vals.splice(index, 1);
        this.saveAttrVals(row);
      }
    }
  }
</script>

<style scoped>
  .cat-opt{
    margin: 15px 0;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag{
    width: 120px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
